import { Request, Response } from 'express'
import { notificationTemplateService } from '../services/notificationTemplate'

export const createTemplate = async (req: Request, res: Response) => {
  try {
    const template = await notificationTemplateService.createTemplate(req.body)
    res.status(201).json(template)
  } catch (error) {
    res.status(400).json({ message: error.message })
  }
}

export const updateTemplate = async (req: Request, res: Response) => {
  try {
    const { code } = req.params
    const template = await notificationTemplateService.updateTemplate(code, req.body)
    if (!template) {
      return res.status(404).json({ message: '模板不存在' })
    }
    res.json(template)
  } catch (error) {
    res.status(400).json({ message: error.message })
  }
}

export const deleteTemplate = async (req: Request, res: Response) => {
  try {
    const { code } = req.params
    const result = await notificationTemplateService.deleteTemplate(code)
    if (result.deletedCount === 0) {
      return res.status(404).json({ message: '模板不存在' })
    }
    res.json({ message: '删除成功' })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
}

export const getTemplate = async (req: Request, res: Response) => {
  try {
    const { code } = req.params
    const template = await notificationTemplateService.getTemplate(code)
    if (!template) {
      return res.status(404).json({ message: '模板不存在' })
    }
    res.json(template)
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
}
